package com.erp.generic.action;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.erp.generic.form.LoginForm;
import com.erp.generic.service.impl.AuthorizationProcessor;
import com.erp.generic.service.impl.BaseAuthenticationProcessor;
import com.erp.generic.utils.SessionManager;


public class LoginAction extends DispatchAction{
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		boolean status = true;
		String redirect = "failure";
		
		LoginForm loginform = (LoginForm)form;
		String userid = loginform.getLoginid();
		String password = loginform.getPassword();
		String sessionId = loginform.getSessionid();
		Map<String, String> sessionDetailsMap = new LinkedHashMap<String, String>();
        request.setAttribute("userid",userid);
		try{
			
			BaseAuthenticationProcessor authenticationProcessor = new AuthorizationProcessor();
			authenticationProcessor.authenticateUser(userid, password, sessionId, sessionDetailsMap);
			
			
//			 Added for using old session while logging in.
			String oldSessionId = null;
			String newSessionId = null;
			try {
				oldSessionId = request.getSession().getId();
				request.getSession().invalidate();
				
			}catch (Exception e) {
			}
			newSessionId = request.getSession().getId();
						
			// PEN SECURITY
			Random random = new Random();
			long tokenId = random.nextLong();
			
			String remorteAddr = request.getRemoteAddr();
			String hostname = request.getRemoteHost();
			sessionDetailsMap.put("tokenId", "" + tokenId);
			sessionDetailsMap.put("oldSessionId", oldSessionId);
			sessionDetailsMap.put("sessionId", newSessionId);
			sessionDetailsMap.put("localIPAddress", remorteAddr);
			sessionDetailsMap.put("localHostName", hostname);
			
			SessionManager.getInstance().setValue(request.getSession(), "sessionDetMap", sessionDetailsMap);
			status = authenticationProcessor.verifyPassword(userid,password,sessionDetailsMap);
			
			if(status){
					redirect = "success";					
				}
			
			request.getSession().setAttribute("userid",userid);
			request.getSession().setAttribute("sessionId", newSessionId);
			
			}
		catch (Exception e) {
			e.printStackTrace();
		}
		if("fail".equalsIgnoreCase(redirect));
		request.setAttribute("errMsg","Kindly enter correct ID and Password");
		
		return mapping.findForward(redirect);
	}

}
